#!/bin/bash
# Comprehensive compilation script for all generated C++ files
# This script attempts to compile each file and logs results

set -e

BASE_DIR="/home/linden/claude/zclaude/conversion-evaluation/04-cpp-generated"
LOG_DIR="/home/linden/claude/zclaude/conversion-evaluation/05-compilation-results/build-logs"

echo "=== C++ Compilation Test Suite ==="
echo "Starting compilation attempts..."
echo ""

# Arrays to track results
declare -a COMPILED_FILES
declare -a FAILED_FILES
declare -i TOTAL_ATTEMPTS=0
declare -i SUCCESSFUL_COMPILES=0

# Function to attempt compilation
compile_file() {
    local repo=$1
    local file=$2
    local basename=$(basename "$file" .cpp)

    echo "----------------------------------------"
    echo "Repository: $repo"
    echo "File: $basename.cpp"
    echo "----------------------------------------"

    TOTAL_ATTEMPTS=$((TOTAL_ATTEMPTS + 1))

    cd "$BASE_DIR/$repo"

    if g++ -std=c++20 -Wall -Wno-unknown-pragmas -c "$basename.cpp" 2>&1 | tee "$LOG_DIR/$repo/${basename}_compile.log"; then
        echo "  ✓ COMPILED SUCCESSFULLY"
        COMPILED_FILES+=("$repo/$basename.cpp")
        SUCCESSFUL_COMPILES=$((SUCCESSFUL_COMPILES + 1))
        # Save object file
        if [ -f "${basename}.o" ]; then
            cp "${basename}.o" "$LOG_DIR/$repo/${basename}.o"
        fi
        return 0
    else
        echo "  ✗ COMPILATION FAILED"
        FAILED_FILES+=("$repo/$basename.cpp")
        return 1
    fi
}

# Compile each repository
compile_file "DotNetCSharpLinqByExample" "pet.cpp"
compile_file "DotNetCSharpLinqByExample" "joins.cpp"
compile_file "DelegateTransform" "delegate_transform.cpp"
compile_file "DelegateTransform" "delegate_transform_tests.cpp"
compile_file "RobloxAPI" "group.cpp"
compile_file "RobloxAPI" "group_role.cpp"
compile_file "RobloxAPI" "http_helper.cpp"
compile_file "RobloxAPI" "outfit.cpp"
compile_file "RobloxAPI" "search_api.cpp"
compile_file "C5" "array_list.cpp"
compile_file "C5" "hash_set.cpp"

echo ""
echo "========================================"
echo "  COMPILATION RESULTS SUMMARY"
echo "========================================"
echo "Total files attempted: $TOTAL_ATTEMPTS"
echo "Successfully compiled: $SUCCESSFUL_COMPILES"
echo "Failed to compile: $((TOTAL_ATTEMPTS - SUCCESSFUL_COMPILES))"
echo "Success rate: $(awk "BEGIN {printf \"%.1f\", ($SUCCESSFUL_COMPILES/$TOTAL_ATTEMPTS)*100}")%"
echo ""

if [ ${#COMPILED_FILES[@]} -gt 0 ]; then
    echo "✓ Successfully compiled files:"
    for file in "${COMPILED_FILES[@]}"; do
        echo "  - $file"
    done
    echo ""
fi

if [ ${#FAILED_FILES[@]} -gt 0 ]; then
    echo "✗ Failed to compile:"
    for file in "${FAILED_FILES[@]}"; do
        echo "  - $file"
    done
fi

echo "========================================"
